<template>
  <div class="table-demo">
    <h1>{{ title }}</h1>
    <BaseTable
      ref="tableRef"
      :table-data="tableData"
      :columns="columns"
      :total="total"
      :loading="loading"
      :page-sizes="pageSizes"
      :current-page="currentPage"
      :page-size="pageSize"
      :selectOptions="statusOptions"
      :showDatePicker="true"
      showOperations
      @search="handleSearch"
      @reset="handleReset"
      @add="handleAdd"
      @edit="handleEdit"
      @delete="handleDelete"
      @export="handleExport"
      @print="handlePrint"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @select-change="handleSelectChange"
      @date-change="handleDateChange"
      @virtual="handleVirtual"
      @load-all-data="handleLoadAllData"
      @update:currentPage="handleCurrentPageChange"
      @update:pageSize="handlePageSizeChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import BaseTable from '../components/BaseTable/index.vue'
import type { TableColumn } from '../components/BaseTable/components/table/types'
import { exportToExcel } from '../utils/exportUtils'

// Define the data structure
interface TableItem {
  id: number
  name: string
  age: number
  gender: string
  email: string
  phone: string
  status: string
  createTime: string
  address: string
}

// 定义表格列
const columns = ref<TableColumn[]>([
  { prop: 'id', label: 'ID', width: 80 },
  { prop: 'name', label: '姓名', width: 120 },
  { prop: 'age', label: '年龄', width: 80 },
  { prop: 'gender', label: '性别', width: 80 },
  { prop: 'email', label: '邮箱', width: 220 },
  { prop: 'phone', label: '电话', width: 150 },
  { prop: 'status', label: '状态', width: 100 },
  { prop: 'createTime', label: '创建时间', width: 180, type: 'text' },
  { prop: 'address', label: '地址' }
])

// 状态选项
const statusOptions = [
  { value: 'active', label: '活跃' },
  { value: 'inactive', label: '不活跃' },
  { value: 'pending', label: '待审核' }
]

// 表格数据
const tableData = ref<TableItem[]>([])
const total = ref(0)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const pageSizes = [10, 20, 50, 100]
const title = ref('用户管理')
const tableRef = ref()
const selectedRows = ref<any[]>([])

// 生成模拟数据
const generateMockData = (): TableItem[] => {
  const data: TableItem[] = []
  const statuses = ['active', 'inactive', 'pending']
  const genders = ['男', '女']
  
  for (let i = 1; i <= 100; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)]
    const gender = genders[Math.floor(Math.random() * genders.length)]
    
    data.push({
      id: i,
      name: `用户${i}`,
      age: Math.floor(Math.random() * 50) + 18,
      gender,
      email: `user${i}@example.com`,
      phone: `1${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10000000000).toString().padStart(9, '0')}`,
      status,
      createTime: new Date(Date.now() - Math.floor(Math.random() * 31536000000)).toISOString(),
      address: `北京市朝阳区某某街道${i}号`
    })
  }
  
  return data
}

// 获取数据
const fetchData = (page = currentPage.value, size = pageSize.value, keyword = '', status = '', dateRange: [string, string] | null = null) => {
  loading.value = true
  
  console.log("Fetching data with page:", page, "size:", size)
  
  // 模拟API请求延迟
  setTimeout(() => {
    const allData = generateMockData()
    
    // 根据状态筛选
    let filteredData = status 
      ? allData.filter(item => item.status === status)
      : allData
    
    // 根据关键词搜索
    if (keyword) {
      const lowerKeyword = keyword.toLowerCase()
      filteredData = filteredData.filter(item => 
        item.name.toLowerCase().includes(lowerKeyword) || 
        item.email.toLowerCase().includes(lowerKeyword) ||
        item.address.toLowerCase().includes(lowerKeyword)
      )
    }
    
    // 根据日期范围过滤
    if (dateRange && dateRange.length === 2) {
      const startDate = new Date(dateRange[0]).getTime()
      const endDate = new Date(dateRange[1]).getTime()
      
      filteredData = filteredData.filter(item => {
        const itemDate = new Date(item.createTime).getTime()
        return itemDate >= startDate && itemDate <= endDate
      })
    }
    
    // 计算分页
    total.value = filteredData.length
    const start = (page - 1) * size
    const end = start + size
    
    tableData.value = filteredData.slice(start, end)
    console.log("Setting tableData:", tableData.value.length, "items")
    
    loading.value = false
  }, 100) // 加快加载速度
}

// 事件处理方法
const handleSearch = (params: { keyword: string, page: number, pageSize: number } | string) => {
  let keyword = '';
  let page = currentPage.value;
  let size = pageSize.value;
  
  if (typeof params === 'object') {
    keyword = params.keyword;
    page = params.page;
    size = params.pageSize;
  } else {
    keyword = params;
  }
  
  fetchData(page, size, keyword)
}

const handleReset = () => {
  currentPage.value = 1
  fetchData(1, pageSize.value)
}

const handleAdd = () => {
  ElMessage.success('触发新增操作')
}

const handleEdit = (row: any) => {
  ElMessage.success(`编辑用户ID: ${row.id}, 名称: ${row.name}`)
}

const handleDelete = (rows: any[]) => {
  const ids = rows.map(row => row.id).join(',')
  
  ElMessageBox.confirm(`确定要删除所选的${rows.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(`删除用户ID: ${ids}`)
  }).catch(() => {
    // 取消操作
  })
}

const handleExport = () => {
  ElMessage.success(`导出数据`)
  exportToExcel(selectedRows.value.length > 0 ? selectedRows.value : tableData.value, 'user_data')
}

const handlePrint = () => {
  ElMessage.success(`打印数据`)
}

const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

const handleRowClick = (row: any) => {
  console.log('行点击', row)
}

const handleSelectChange = (value: string | number) => {
  const strValue = value.toString()
  fetchData(1, pageSize.value, '', strValue)
}

const handleDateChange = (dateRange: [string, string] | null) => {
  fetchData(1, pageSize.value, '', '', dateRange)
}

const handleVirtual = () => {
  console.log('Virtual filter triggered')
  ElMessage.success('打开高级过滤')
}

// Load all data for virtual scrolling mode
const handleLoadAllData = ({ limit }: { limit: number }) => {
  const allData = generateMockData();
  tableData.value = allData.slice(0, limit);
}

const handleCurrentPageChange = (page: number) => {
  currentPage.value = page
  fetchData(page, pageSize.value)
}

const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  fetchData(currentPage.value, size)
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.table-demo {
  width: 100%;
}

h1 {
  margin-bottom: 20px;
  font-size: 24px;
}
</style> 